<style type="text/css">
    .el-product-spec-warp{border-bottom: 1px dashed #C0C4CC;margin-bottom: 20px}
    .el-product-spec-choose{margin-bottom: 16px}
    .el-product-spec-item{margin-bottom: 10px;border: 1px solid #eeee;padding: 10px 15px;position: relative;}
    .el-product-spec-item-header{height: 40px;}
    .el-product-spec-item-header-title{vertical-align: middle}
    .el-product-spec-item-header-radio{margin:0 20px;vertical-align: middle}
    .el-product-spec-item-header-move{font-size: 22px;cursor: move;vertical-align: middle}
    .el-product-spec-item-value{display: inline-block;font-size:0;margin-right: 10px;margin-bottom: 10px}
    .el-product-spec-item-value-add{width:200px;vertical-align: middle!important;}
    .el-product-spec-item-value-move{cursor: move;}
    .el-product-spec-item-add{margin-bottom: 20px;width:300px;vertical-align: unset!important;}
    .el-product-spec .el-input-group__append{padding:0}
    .el-product-spec .el-input-group__append span{display: inline-block;min-width: 50px;height: 29px;text-align: center;cursor: pointer;line-height: 29px;padding:0 5px;}
</style>
<script>
    /**
     * 产品规格组件
     */
    Vue.component('el-product-spec', {
        template:`
        <div class="el-product-spec">
            <draggable class="el-product-spec-warp" v-model="spec" v-bind="draggable">
                <div 
                    class="el-product-spec-item"
                    v-for="(item, index) in spec" 
                    :key="index">
                    <div class="el-product-spec-item-header">
                        <span class="el-product-spec-item-header-title">{{item.title}}<i class="el-icon-error" @click="removeItem(index)"></i></span>
                        <el-radio-group class="el-product-spec-item-header-radio" v-model="item.type">
                            <el-radio :label="0">文字</el-radio>
                            <el-radio :label="1">颜色</el-radio>
                            <el-radio :label="2">图片</el-radio>
                        </el-radio-group>
                        <i class="el-icon-rank el-product-spec-item-header-move"></i>
                    </div>
                    <draggable v-model="item.value" v-bind="draggableValue">
                        <div 
                            class="el-product-spec-item-value"
                            v-for="(itemValue, indexValue) in item.value"
                            :key="indexValue">
                            <el-tag 
                                class="el-product-spec-item-value-move"
                                @close="removeValueItem(index, indexValue)"
                                closable>
                                {{item.value[indexValue]['title']}}
                            </el-tag>
                            <el-color-picker 
                                size="small"
                                v-if="item.type === 1" 
                                v-model="item.value[indexValue]['color']" 
                                style="vertical-align: top;">
                            </el-color-picker>
                            <el-file-select 
                                v-if="item.type === 2" 
                                v-model="item.value[indexValue]['cover']" 
                                :size="32">
                            </el-file-select>
                        </div>
                        <el-input
                            class="el-product-spec-item-value-add"
                            size="small"
                            v-model="ValueItemTitle[index]"
                            placeholder="请输入属性名称比如：蓝色"
                            @keyup.enter.native="addValueItem(index)">
                            <template slot="append"><span @click="addValueItem(index)">添加</span></template>
                        </el-input>
                    </draggable>
                </div>
                <el-input
                    class="el-product-spec-item-add"
                    size="small"
                    v-model="itemTitle" 
                    placeholder="规格名称比如：颜色"
                    @keyup.enter.native="addItem()">
                    <template slot="append"><span @click="addItem()">添加新规格</span></template>
                </el-input>
                <el-button
                    size="small"
                    type="success"
                    @click="skuChange()">
                    立即生成
                </el-button>
            </draggable>
            <p>批量设置：</p>
            <el-table :data="[{}]" border>
                <el-table-column label="图片">
                    <template slot-scope="scope">
                        <el-file-select v-model="batchSetting.cover"></el-file-select>
                    </template>
                </el-table-column>
                <el-table-column label="划线价">
                    <template slot-scope="scope">
                        <el-input type="number" v-model="batchSetting.line_price"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="销售价">
                    <template slot-scope="scope">
                        <el-input type="number" v-model="batchSetting.sale_price"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="库存">
                    <template slot-scope="scope">
                        <el-input type="number" v-model="batchSetting.stock"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="编码">
                    <template slot-scope="scope">
                        <el-input v-model="batchSetting.code"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="重量(KG)">
                    <template slot-scope="scope">
                        <el-input type="number" v-model="batchSetting.weight"></el-input>
                    </template>
                </el-table-column>
            </el-table>
            <p>商品属性：</p>
            <el-table
                :data="sku"
                :span-method="skuRowspan"
                border>
                <el-table-column 
                    v-for="(item, index) in spec" 
                    :key="index"
                    :prop="'prop' + index" 
                    :label="item.title">
                </el-table-column>
                <el-table-column prop="cover" label="图片">
                    <template slot-scope="scope">
                        <el-file-select v-model="scope.row.cover"></el-file-select>
                    </template>
                </el-table-column>
                <el-table-column prop="line_price" label="划线价">
                    <template slot-scope="scope">
                        <el-input type="number" v-model="scope.row.line_price"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="sale_price" label="销售价">
                    <template slot-scope="scope">
                        <el-input type="number" v-model="scope.row.sale_price"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="stock" label="库存">
                    <template slot-scope="scope">
                        <el-input type="number" v-model="scope.row.stock"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="code" label="编码">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.code"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="weight" label="重量(KG)">
                    <template slot-scope="scope">
                        <el-input type="number" v-model="scope.row.weight"></el-input>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        `,
        props: {
            value: {
                type: Array,
                default: [],
            },
        },
        data() {
            return {
                templates: [],
                template: [],
                spec: this.value[0],
                sku: this.value[1],
                itemTitle: "",
                ValueItemTitle: [],
                batchSetting: {
                    cover: "",
                    code: "", 
                    line_price: 0.00, 
                    sale_price: 0.00,
                    weight: 0,
                    stock: 0.00, 
                },
                draggable: {
                    handle: '.el-product-spec-item-header-move',
                    animation: 300,
                    forceFallback: true,
                },
                draggableValue: {
                    handle: '.el-product-spec-item-value-move',
                    animation: 300,
                    forceFallback: true,
                }
            }
        },
        created() {
            this.skuInit();
        },
        methods: {
            /**
             * sku初始化
             */
            skuInit() {
                this.sku.forEach(function (item, index) {
                    let prop = item['title'].split(',');
                    prop.forEach(function (val, key) {
                        let propKey   = 'prop' + key;
                        item[propKey] = val;
                    });
                })
            },
            
            /**
             * 新增规格
             */
            addItem() {
                if (this.itemTitle != "") {
                    if (common.arrayIndex(this.spec, this.itemTitle, 'title') === -1) {
                        this.spec.push({title: this.itemTitle, type: 0, value: []});
                        this.itemTitle = "";
                    } else {
                        this.$notify({ showClose: true, message: '规格名称不能重复', type: 'error'});
                    }
                } else {
                    this.$notify({ showClose: true, message: '规格名称不能为空', type: 'error'});
                }
            },
    
            /**
             * 删除规格
             * @param {int} index 下标
             */
            removeItem(index) {
                this.spec.splice(index, 1);
            },
    
            /**
             * 新增规格项
             * @param {int} index 下标
             */
            addValueItem(index) {
                if (typeof this.ValueItemTitle[index] !== "undefined" && this.ValueItemTitle[index] !== "") {
                    if (common.arrayIndex(this.spec[index]['value'], this.ValueItemTitle[index], 'title') === -1) {
                        this.spec[index]['value'].push({title: this.ValueItemTitle[index], cover: "", color: ""});
                        this.$set(this.ValueItemTitle, index, "");
                    } else {
                        this.$notify({ showClose: true, message: '属性名称不能重复', type: 'error'});
                    }
                } else {
                    this.$notify({ showClose: true, message: '属性名称不能为空', type: 'error'});
                }
            },
    
            /**
             * 删除规格项
             * @param {int} index      规格下标
             * @param {int} indexValue 规格项下标
             */
            removeValueItem(index,indexValue) {
                this.spec[index]['value'].splice(indexValue, 1);
            },
    
            /**
             * 批量设置
             */
            batchSet() {
                let self = this;
                self.sku.forEach(function (item, index) {
                    item['cover']          = self.batchSetting.cover;
                    item['code']           = self.batchSetting.code;
                    item['line_price'] = self.batchSetting.line_price;
                    item['sale_price']     = self.batchSetting.sale_price;
                    item['weight']         = self.batchSetting.weight;
                    item['stock']          = self.batchSetting.stock;
                    self.$set(self.sku, index, item);
                });
            },
            
            /**
             * 批量清空
             */
            batchReset() {
                this.batchSetting = {
                    cover: "",
                    code: "", 
                    line_price: 0.00, 
                    sale_price: 0.00,
                    weight: 0,
                    stock: 0.00, 
                }
            },
            
            /**
             * sku列表改变
             */
            skuChange() {
                let self = this;
                // 排列组合
                let arr  = [];
                self.spec.forEach(function (item, index) {
                    if (item.value.length > 0) {
                        if (index === 0) {
                            item.value.forEach(function (val, key) {
                                arr.push(val.title);
                            })
                        } else {
                            arr = self.specData(arr, item.value);
                        }
                    }
                });
                // 生成列表
                let sku  = [];
                arr.forEach(function (item, index) {
                    let spec   = item.split(',');
                    let defaul = {cover: "", code: "", line_price: 0.00, sale_price: 0.00, stock: 0.00, weight: 0}
                    let single = typeof self.sku[index] === 'undefined' ? defaul : self.sku[index];
                    spec.forEach(function (val, key) {
                        let prop = 'prop' + key;
                        single[prop] = val;
                    });
                    single['title'] = item;
                    sku.push(single);
                });
                self.sku = sku;
                self.$emit('input', [self.spec, self.sku]);
            },
    
            /**
             * 排列组合
             * @param {array} itemArr   全部数组
             * @param {array} itemValue 规格项
             */
            specData(itemArr, itemValue) {
                let arr = [];
                itemArr.forEach(function (item, index) {
                    itemValue.forEach(function (val, key) {
                        arr.push(item + ',' + val.title);
                    })
                })
                return arr;
            },
    
            /**
             * 表格展示
             */
            skuRowspan({ row, column, rowIndex, columnIndex }) {
                let self  = this;
                let count = self.spec.length;
                let span  = "";
                self.spec.forEach(function (item, index) {
                    if (columnIndex === index) {
                        if (count > index + 1) {
                            let remainder = 1;
                            self.spec.forEach(function (val, key) {
                                if (key > index) {
                                    remainder = remainder * val['value'].length;
                                }
                            });
                            if (remainder > 0) {
                                if (rowIndex % remainder === 0) {
                                    span = {rowspan: remainder, colspan: 1};
                                } else {
                                    span = {rowspan: 0, colspan: 0};
                                }
                            }
                        }
                    }
                });
                return span;
            },
            /**
             * 远程搜索规格模板
             */
            remoteMethod(query) {
                if (query !== '') {
                    let self = this;
                    request.post('shop/shopSpec/index', {keyword: query}, function(res){
                        if (res.status === 'success') {
                            self.templates = res.data;
                        } else {
                            self.$notify({ showClose: true, message: res.message, type: res.status});
                        }
                    });
                } else {
                    self.templates = [];
                }
            },
        },
        watch: {
            value(v) {
                this.spec = v[0];
                this.sku  = v[1];
                this.skuInit();
            },
        }
    })
</script>